<template>
  <div class="ansible-credentials">
    <div class="page-header">
      <h2>🔑 凭据管理</h2>
      <button class="btn btn-primary" @click="showAddModal = true">+ 添加凭据</button>
    </div>

    <div v-if="!credentials || credentials.length === 0" class="empty-state">
      <div class="empty-icon">🔑</div>
      <p>暂无凭据</p>
      <p class="empty-hint">点击右上角"添加凭据"按钮创建SSH凭据</p>
    </div>

    <div class="credentials-grid" v-else>
      <div v-for="cred in credentials" :key="cred.id" class="credential-card">
        <div class="card-header">
          <div class="header-left">
            <h3>{{ cred.name }}</h3>
            <span class="credential-type-badge" :class="`type-${cred.credential_type}`">
              {{ getTypeText(cred.credential_type) }}
            </span>
          </div>
          <div class="card-actions">
            <button class="btn btn-sm" @click="editCredential(cred)">编辑</button>
            <button class="btn btn-sm btn-danger" @click="deleteCredential(cred.id)">删除</button>
          </div>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="label">用户名:</span>
            <span class="value">{{ cred.username || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">密码:</span>
            <span class="value">{{ cred.password }}</span>
          </div>
          <div class="info-row">
            <span class="label">提权方式:</span>
            <span class="value">{{ cred.become_method }}</span>
          </div>
          <div class="info-row">
            <span class="label">提权用户:</span>
            <span class="value">{{ cred.become_user }}</span>
          </div>
          <div class="info-row" v-if="cred.description">
            <span class="label">描述:</span>
            <span class="value">{{ cred.description }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑凭据弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑凭据' : '添加凭据' }}</h3>
          <button class="btn-close" @click="closeModal">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveCredential">
            <div class="form-group">
              <label>凭据名称 *</label>
              <input v-model="formData.name" required placeholder="例如: 生产环境SSH" />
            </div>

            <div class="form-group">
              <label>凭据类型 *</label>
              <div class="radio-group">
                <label class="radio-item">
                  <input type="radio" v-model="formData.credential_type" value="ssh_password" />
                  <span>🔐 SSH密码</span>
                </label>
                <label class="radio-item">
                  <input type="radio" v-model="formData.credential_type" value="ssh_key" />
                  <span>🔑 SSH密钥</span>
                </label>
              </div>
            </div>

            <div class="form-group">
              <label>用户名 *</label>
              <input v-model="formData.username" required placeholder="例如: root" />
            </div>

            <!-- 密码登录 -->
            <div v-if="formData.credential_type === 'ssh_password'" class="form-group">
              <label>密码 *</label>
              <input type="password" v-model="formData.password" required placeholder="SSH密码" />
            </div>

            <!-- 密钥登录 -->
            <div v-if="formData.credential_type === 'ssh_key'" class="form-group">
              <label>SSH私钥 *</label>
              <textarea v-model="formData.ssh_key" required rows="8" 
                placeholder="-----BEGIN RSA PRIVATE KEY-----&#10;...&#10;-----END RSA PRIVATE KEY-----"></textarea>
            </div>

            <div class="form-group">
              <label>提权方式</label>
              <select v-model="formData.become_method">
                <option value="sudo">sudo</option>
                <option value="su">su</option>
                <option value="pbrun">pbrun</option>
                <option value="pfexec">pfexec</option>
              </select>
            </div>

            <div class="form-group">
              <label>提权用户</label>
              <input v-model="formData.become_user" placeholder="默认: root" />
            </div>

            <div class="form-group">
              <label>提权密码</label>
              <input type="password" v-model="formData.become_password" placeholder="可选" />
            </div>

            <div class="form-group">
              <label>描述</label>
              <textarea v-model="formData.description" rows="2" placeholder="可选描述信息"></textarea>
            </div>

            <div class="form-actions">
              <button type="button" class="btn" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../services/api'

const credentials = ref([])
const showAddModal = ref(false)
const showEditModal = ref(false)
const formData = ref({
  name: '',
  credential_type: 'ssh_password',
  username: '',
  password: '',
  ssh_key: '',
  become_method: 'sudo',
  become_user: 'root',
  become_password: '',
  description: ''
})

const loadData = async () => {
  try {
    const data = await api.getCredentials()
    credentials.value = Array.isArray(data) ? data : (data.results || [])
    console.log('加载成功，凭据数量:', credentials.value.length)
  } catch (error) {
    console.error('加载凭据失败:', error)
    credentials.value = []
    alert('❌ 加载凭据失败: ' + (error.response?.data?.error || error.message))
  }
}

const getTypeText = (type) => {
  const map = {
    'ssh_password': '🔐 密码',
    'ssh_key': '🔑 密钥',
    'vault': '🔒 Vault'
  }
  return map[type] || type
}

const editCredential = (cred) => {
  formData.value = {
    id: cred.id,
    name: cred.name,
    credential_type: cred.credential_type,
    username: cred.username,
    password: '',
    ssh_key: '',
    become_method: cred.become_method,
    become_user: cred.become_user,
    become_password: '',
    description: cred.description
  }
  showEditModal.value = true
}

const saveCredential = async () => {
  try {
    const data = { ...formData.value }
    
    // 清理不需要的字段
    if (data.credential_type === 'ssh_password') {
      delete data.ssh_key
    } else if (data.credential_type === 'ssh_key') {
      delete data.password
    }
    
    if (showEditModal.value) {
      await api.updateCredential(data.id, data)
      alert('✅ 更新成功')
    } else {
      await api.createCredential(data)
      alert('✅ 添加成功')
    }
    closeModal()
    loadData()
  } catch (error) {
    console.error('保存失败:', error)
    const errorMsg = error.response?.data?.error || error.response?.data?.detail || error.message
    alert('❌ 保存失败: ' + errorMsg)
  }
}

const deleteCredential = async (id) => {
  if (!confirm('确定要删除这个凭据吗？')) return
  try {
    await api.deleteCredential(id)
    alert('删除成功')
    loadData()
  } catch (error) {
    alert('删除失败: ' + (error.response?.data?.error || error.message))
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    name: '',
    credential_type: 'ssh_password',
    username: '',
    password: '',
    ssh_key: '',
    become_method: 'sudo',
    become_user: 'root',
    become_password: '',
    description: ''
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
@import '../styles/ansible-theme.css';

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.credential-type-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  border: 2px solid;
}

.type-ssh_password {
  background: linear-gradient(135deg, rgba(18, 202, 214, 0.2), rgba(18, 202, 214, 0.1));
  color: var(--color-accent-blue);
  border-color: var(--color-accent-blue);
}

.type-ssh_key {
  background: linear-gradient(135deg, rgba(255, 215, 0, 0.2), rgba(255, 215, 0, 0.1));
  color: #FFD700;
  border-color: #FFD700;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: var(--color-bg-primary);
  border: 2px solid var(--color-border);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.radio-item:hover {
  border-color: var(--color-accent-pink);
  background: var(--color-bg-tertiary);
}

.radio-item input[type="radio"] {
  width: 18px;
  height: 18px;
  accent-color: var(--color-accent-pink);
}

.radio-item span {
  color: var(--color-text-primary);
  font-weight: 600;
}

.form-group textarea {
  resize: vertical;
  font-family: 'Consolas', 'Monaco', monospace;
}
</style>
